package com.etc.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.etc.entity.Users;
import com.etc.service.UsersService;
import com.etc.service.impl.UsersServiceImpl;
import com.google.gson.Gson;


/**
 * 
 * @author 吉旭、孝梅
 *
 */
@WebServlet("/rs.do")
public class RegisterServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private UsersService uService = new UsersServiceImpl(); 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RegisterServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置请求、响应编码
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		String op ="query";
		if(request.getParameter("op") != null) {
			op = request.getParameter("op");
		}
		if(op.equals("query")) {
			
		}else if(op.equals("add")) {
			//修改,接收JSON格式数据
			//以整体形势接收
			//request.getReader()  这个方法是从页面一侧获取ajax请求的json数据
			BufferedReader reader = request.getReader();
			StringBuffer sBuffer = new StringBuffer();
			String str = null;
			while((str = reader.readLine()) != null) {
				//将数据添加到sBuffer中
				sBuffer.append(str);
			}
			
			//将sBuffer的json格式数据转换为users对象
			Gson gson = new Gson();
			Users users = gson.fromJson(sBuffer+"", Users.class);
			System.out.println(users);
			
			
			//将修改后的数据存回数据库
			boolean flag = uService.AddUsers(users);
			
			//返回结果 让前台接收完给弹窗提示  成功或失败
			PrintWriter out = response.getWriter();
			out.print(flag);
			out.close();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
